package breadbox.dataManagement;

import java.io.IOException;
import java.rmi.UnmarshalException;

import breadbox.client.operations.OperationType;
import breadbox.pastry.Message;

public class LocalManager extends Manager {

	public LocalManager() throws IOException {
		storage = new DiskStorage("breadboxStorage");
		//repManager = new LocalReplicationManager(this);
	}
	public static void main(String[] args) throws Exception{
			
		Manager lm = new LocalManager();
		lm.startRMI();
		//lm.startReplication();
	}
	
	// this method is called by the client to get,put,or delete a chunk
	//the chunk is assumed to be on this local machine
	public void sendMessage(Message m) {
		System.out.println("server received call from sendMessage of type " + m.key);
		OperationType t = OperationType.valueOf(m.key);
		
		switch(t) {
			case INITIALIZE: {
				initializeClient(m);
				break;
			}
			case PUT: {
				try {
					byte[] d = m.data;
					storage.write(m.to, d);
					System.err.println("adding " + m.to + " to queue");
					//replicateChunk(m.to);
				}
				catch(Exception e) {
					e.printStackTrace();
				}
				break;
			}
			case DELETE: {
				//delete the chunk, don't send anything to client or pastry
				try {
					storage.delete(m.to);
					//replicateRemoveChunk(m.to);
				}
				catch(Exception e) {
					System.err.println("could not delete");
				}
				break;
			}
			case GET: {
				Message returnMessage;
				//retrieve chunk from storage system and send it through pastry
				try {
					byte[] data = storage.get(m.to);
					//m does not contain m.from since pastry would be the one setting it
					long toID = 0;//new Long(m.from.toString(10));
					returnMessage = new Message(toID, "GET_RESPONSE", data);
				}
				catch(Exception e) {
					e.printStackTrace();
					returnMessage = new Message(0,"GET_ERROR",null);
				}
				try {
					client.sendMessage(returnMessage);
				}
				catch (UnmarshalException e) {
					// do nothing, the client is done
				}
				catch(Exception e) {
					System.err.println("could not send GET back to client");
					e.printStackTrace();
				}
				break;
			}
			case GET_RESPONSE: {
				//pass message to client
				try {
					client.sendMessage(m);
				}
				catch(Exception e) {
					e.printStackTrace();
				}
				break;
			}
			case GET_ERROR: {
				//pass message to client
				try {
					client.sendMessage(m);
				}
				catch(Exception e) {
					e.printStackTrace();
				}
				break;
			}
			default: 
				return;
		}
		//System.out.println("server sendMessage() -at end");
	}
	
	//should not be used since all data is locally stored
	public int route(Message m) {
		return 0;
	}
}
